package com.k12.admim.service.impl;

import com.k12.admim.model.entity.sys.SysDept;
import com.k12.admim.model.vo.sys.SysDeptVo;
import com.k12.admim.rpc.UserFeignClient;
import com.k12.admim.service.OperatorDeptService;
import com.k12.common.model.resp.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OperatorDeptServiceImpl implements OperatorDeptService {

    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public List<SysDeptVo> selectDeptList(SysDeptVo dept) {
        return userFeignClient.getAllDepts(dept);
    }

    @Override
    public boolean checkDeptNameUnique(SysDeptVo dept) {
        Long deptId = dept.getDeptId() != null ? -1L : dept.getDeptId();
        List<SysDeptVo> info = userFeignClient.getAllDepts(dept);
        if (info != null && info.get(0).getDeptId().longValue() != deptId.longValue())
        {
            return false;
        }
        return true;
    }

    @Override
    public R insertDept(SysDeptVo dept) {
        SysDept info = userFeignClient.selectDeptById(dept.getParentId(),dept.getTenantId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!"0".equals(info.getStatus())) {
            return R.failed("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        userFeignClient.insertDept(dept);
        return R.success();
    }

    @Override
    public boolean checkDeptDataScope(Long deptId, String tenantId) {
        SysDept sysDept = userFeignClient.selectDeptById(deptId, Long.valueOf(tenantId));
        if (sysDept != null) {
            return true;
        }else{
            return false;
        }
    }

    @Override
    public R selectDeptById(Long deptId,String tenantId) {
        SysDept sysDept = userFeignClient.selectDeptById(deptId, Long.valueOf(tenantId));
        return R.success(sysDept);
    }

    @Override
    public int selectNormalChildrenDeptById(Long deptId,String tenantId) {
        return userFeignClient.selectNormalChildrenDeptById(deptId, Long.valueOf(tenantId));
    }

    @Override
    public void updateDept(SysDeptVo dept) {
        userFeignClient.updateDept(dept);
    }

    @Override
    public boolean hasChildByDeptId(Long deptId,String tenantId) {
        int i = userFeignClient.hasChildByDeptId(deptId, tenantId);
        if (i > 0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean checkDeptExistUser(Long deptId, String tenantId) {
        int result = userFeignClient.checkDeptExistUser(deptId,tenantId);
        return result > 0;
    }

    @Override
    public void deleteDeptById(Long deptId, String tenantId) {
        userFeignClient.deleteDeptById(deptId, tenantId);
    }
}
